package com.hua.store.web.servlet;

import com.hua.store.domin.User;
import com.hua.store.service.UserService;
import com.hua.store.service.impl.UserServiceImpl;
import com.hua.store.utils.CookUtils;
import com.hua.store.utils.MailUtils;
import com.hua.store.utils.MyBeanUtils;
import com.hua.store.utils.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

public class UserServlet extends BaseServlet {
    /**
     * 使用servlet跳转到jsp/register.jsp,代替a标签
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String registerUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return "/jsp/register.jsp";
    }


    /**
     * 使用servlet跳转到jsp/login.jsp,代替a标签
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String loginUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return "/jsp/login.jsp";
    }


    /**
     * 实现用户注册的servlet
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String userRegister(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//        req.setCharacterEncoding("UTF-8");
//        resp.setContentType("text/html;charset:utf-8");
//        System.out.println("11111");
        Map<String, String[]> map = req.getParameterMap();

        User user = new User();

        MyBeanUtils.populate(user, map);

//        System.out.println("222");
        user.setUid(UUIDUtils.getId());
        user.setState(0);
        user.setCode(UUIDUtils.getCode());

        //测试打印
//        System.out.println("333");

        UserService service = new UserServiceImpl();
        try {
            service.userRegister(user);
            req.setAttribute("msg", "注册成功，请前往邮箱尽快激活");
            req.setAttribute("flag", 1);
            MailUtils.sendMail(user.getEmail(), user.getCode());
        } catch (SQLException e) {
            e.printStackTrace();
            req.setAttribute("msg", "注册失败，请重新注册");
            req.setAttribute("flag", 0);
        }
        return "/jsp/test.jsp";
    }

    /**
     * 实现用户激活的servlet
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String active(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        UserService service = new UserServiceImpl();
        User user = service.userActive(code);
        if (user != null) {
            user.setState(1);
            user.setCode("");
            service.userActiveLate(user);
            req.setAttribute("msg", "激活成功，请登录");
            return "/jsp/login.jsp";
        } else {
            req.setAttribute("msg", "激活失败，请重新激活");
            return "/jsp/test.jsp";
        }
    }


    /**
     * 实现用户登录的servlet
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String userLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String autoLogin = req.getParameter("auto_login");
//        String username = req.getParameter("username");

        User user = new User();
        Map<String, String[]> map = req.getParameterMap();
        MyBeanUtils.populate(user, map);
        UserService service = new UserServiceImpl();
        User user1 = null;
        try {
            user1 = service.userLogin(user);
            if (user1 != null) {
                if ("on".equals(autoLogin)) {
                    Cookie cookie = new Cookie("auto_login", user1.getUsername() + "#hua#" + user1.getPassword());
                    cookie.setPath("/");
                    cookie.setMaxAge(60 * 60 * 24 * 7);
                    resp.addCookie(cookie);
                }

                String rem = req.getParameter("rememberMe");

                if ("on".equals(rem)) {
//                    System.out.println(user1.getUsername());
                    Cookie cookie = new Cookie("remUser", user1.getUsername());
                    cookie.setMaxAge(60 * 60 * 24 * 70);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }

                req.getSession().setAttribute("loginUser", user1);
                resp.sendRedirect("/index.jsp");
            } else {
                req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);

            }

            return null;
        } catch (Exception e) {
            String msg = e.getMessage();
//            System.out.println(msg);
            req.setAttribute("msg", msg);
            return "/jsp/login.jsp";
        }
    }

    /**
     * 检查用户名是否存在
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String checkUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String username = req.getParameter("username");
        UserService service = new UserServiceImpl();
        boolean b = service.checkUser(username);
        if (b) {
            resp.getWriter().write("<font style='color: green'>用户名可用</font>");
        } else {
            resp.getWriter().write("<font style='color: red'>用户名不存在</font>");
        }
        return null;
    }

    /**
     * 用户退出登录功能
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public String logOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        //清除session
        req.getSession().invalidate();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            Cookie autoLogin = CookUtils.getCookieByName("auto_login", cookies);
            if (autoLogin != null) {
                autoLogin.setMaxAge(0);
                autoLogin.setPath("/");
                resp.addCookie(autoLogin);
            }
        }
        //重定向到首页
        resp.sendRedirect("/index.jsp");
        return null;
    }

}
